#include<iostream>
#include <cstdlib>
//#include "swf.h"
#include "DefineText2.h"
using namespace std;
using namespace swfstream;
DefineText2* DefineText2::from_file(FILE* f) {
	//	int size_read=0;
	//puts("reading define_text2");
	struct DefineText2* r = new DefineText2;
	fread(&r->CharacterID, 2, 1, f);
	//	size_read+=2;
	r->TextBounds = Rect::from_file(f);
	r->TextBounds->print();
	//	size_read+=r->TextBounds->size_in_file();
	r->TextMatrix = Matrix::from_file(f);
	r->TextMatrix->print();
	//	size_read+=r->TextMatrix->size_in_file();
	r->GlyphBits = fgetc(f);
	//	size_read+=1;
	//printf("GlyphBits:%u,",(unsigned)r->GlyphBits);
	r->AdvanceBits = fgetc(f);
	//	size_read+=1;
	//printf("AdvanceBits:%u\n",(unsigned)r->AdvanceBits);
	//	printf("total size=%d\n",size_read);
	r->TextRecords = TextRecord::list_from_file(f, true, r->GlyphBits,
			r->AdvanceBits);
	//printf("$$$$$$$$$$$$$$$$$$$$$$$$$$$,r->TextRecords=%p\n",r->TextRecords);
	if (fgetc(f) != 0) {
		fprintf(stderr, "definetext2:Reserved must be set to 0\n");
		exit(1);
	}
	//puts("define text2 done");
	//printf("$$$$$$$$$$$$$$$$$$$$$$$$$$$,r->TextRecords=%p\n",r->TextRecords);
	return r;
}
void DefineText2::print() {
	Tag::print();
	cout << "define_text2::CharacterID:" << (uint) CharacterID
			<< ",TextBounds:";
	TextBounds->print();
	cout << ",TextMatrix:";
	TextMatrix->print();
	for (uint i = 0; i < TextRecords->size(); i++) {
		TextRecords->at(i)->print();
	}
	/*
	 for(uint j=0;j<TextRecords->size();j++){
	 text_record* record=TextRecords->at(j);
	 for(uint i=0;i<record->GlyphEntries->size();i++){
	 uint index=record->GlyphEntries->at(i)->GlyphIndex;
	 void* codes=font->CodeTable;
	 //to gbk
	 if(font->FontFlagsWideCodes){
	 iconv_t cd=iconv_open("GBK","UCS-2LE");
	 int16 in_buf=*(((uint16*)codes)+index);
	 char* in=(char*)&in_buf;
	 size_t in_left=2;
	 size_t out_left=7;
	 char* out=new char[10];
	 char*outbuf=out;
	 size_t iconv_r=iconv(cd,&in,&in_left,&outbuf,&out_left);
	 //		fprintf(html,"<span style=\"");
	 //		fprintf(html,"\">",out);
	 printf("%s",out);
	 //		fprintf(html,"</span>");
	 }else{
	 exit(3);
	 }
	 }
	 }
	 putchar('\n');
	 */
}
TiXmlElement* DefineText2::toTiXmlElement() {
	TiXmlElement* r = new TiXmlElement("DefineText2");
	r->SetAttribute("CharacterID", CharacterID);
	r->SetAttribute("GlyphBits", GlyphBits);
	r->SetAttribute("AdvanceBits", AdvanceBits);
	TiXmlElement* tmp = new TiXmlElement("textBounds");
	tmp->LinkEndChild(TextBounds->toTiXmlElement());
	r->LinkEndChild(tmp);
	tmp = new TiXmlElement("textMatrix");
	tmp->LinkEndChild(TextMatrix->toTiXmlElement());
	r->LinkEndChild(tmp);
	tmp = new TiXmlElement("textRecords");
	for (int i = 0; i < TextRecords->size(); i++) {
		TiXmlElement* tmp2 = TextRecords->at(i)->toTiXmlElement();
		tmp->LinkEndChild(tmp2);
	}
	r->LinkEndChild(tmp);
	return r;
}
